#pragma once
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<iostream>
#include<string>
#include<cstring>

namespace wyl
{
    class Sock
    {
    public:
        static int Socket()
        {
            int sock = socket(AF_INET,SOCK_STREAM,0);
            if(sock < 0) 
            {
                std::cerr << " socket error" << errno << std::endl;
                exit(-1);
            }
            return sock;
        }
        static void Bind(int sock , uint16_t port)
        {
            struct sockaddr_in server;
            memset(&server,0,sizeof server);
            server.sin_family = AF_INET;
            server.sin_port = htons(port);
            server.sin_addr.s_addr = INADDR_ANY;
            if(bind(sock,(struct sockaddr*)&server,sizeof(server)) < 0)
            {
                std::cerr << " bind error" << errno << std::endl;
                exit(-2);
            }
            std::cout << "bind success" << std::endl;
        }
        static void Listen(int sock)
        {
            if(listen(sock,5) < 0)
            {
                std::cerr << " Listen error" << errno << std::endl;
                exit(-3);
            }
        }
        static int Accept(int sock)
        {
            struct sockaddr_in peer;
            memset(&peer,0,sizeof peer);
            socklen_t len;
            int fd = accept(sock,(struct sockaddr*)&peer,&len);
            if(fd < 0)
            {
                return -1;
            }
            return fd;
        }

        static void Connect(int sock , std::string ip ,uint16_t port)
        {
            struct sockaddr_in ser;
            memset(&ser,0,sizeof ser);
            ser.sin_family = AF_INET;
            ser.sin_port = htons(port);
            ser.sin_addr.s_addr = inet_addr(ip.c_str());
            if(connect(sock,(struct sockaddr*)&ser,sizeof ser) < 0)
            {
                exit(-3);
            }
            std::cout << "connect success " << std::endl;
        }

    };
}